package history.study.array;

// 34. 在排序数组中查找元素的第一个和最后一个位置:https://leetcode-cn.com/problems/find-first-and-last-position-of-element-in-sorted-array/
public class LeetCode_34 {
    public int[] searchRange(int[] nums, int target) {
        if (nums.length <=0) return new int[]{-1,-1};
        int leftIndex = getLeftIndex(nums, target);
        int  rightIndex = getRightIndex(nums, target);
        if (leftIndex > rightIndex) return new int[]{-1,-1};
        return new int[]{leftIndex, rightIndex};
    }

    private int getLeftIndex(int []nums, int target) {
        int left = 0, right = nums.length-1;
        while (left <= right) {
            int mid = left + ((right-left)>>1);
            if (nums[mid] >= target) {
                right = mid-1;
            } else {
                left = mid+1;
            }
        }
        return left;
    }

    private int getRightIndex(int []nums, int target) {
        int left = 0, right = nums.length-1;
        while (left <= right) {
            int mid = left + ((right-left)>>1);
            if (nums[mid] > target) {
                right = mid -1;
            } else {
                left = mid+1;
            }
        }
        return right;
    }
}
